package web.servlet;



import com.alibaba.fastjson.JSONObject;

import com.rdc.example.bean.Result;
import com.rdc.example.bean.dto.UserDTO;
import com.rdc.example.service.UserService;
import com.rdc.example.service.VerificationCodeService;
import com.rdc.example.service.impl.UserServiceImpl;
import com.rdc.example.service.impl.VerificationCodeServiceImpl;
import org.apache.commons.fileupload.FileItem;

import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import java.io.File;

import java.io.PrintWriter;
import java.math.BigDecimal;
import java.util.List;

import static com.rdc.example.util.FileUtil.uploadFile;


@WebServlet("/user/*")
@MultipartConfig
public class UserServlet extends BaseServlet {

    UserServiceImpl userService = new UserServiceImpl();
    VerificationCodeServiceImpl verificationCodeService=new VerificationCodeServiceImpl();

    public void space(HttpServletRequest request, HttpServletResponse response) throws Exception {
        System.out.println("space...");
        //从session获取user
        HttpSession session = request.getSession();
        UserDTO userDTO = (UserDTO) session.getAttribute("userDTO");
        String userName = userDTO.getUserName();
        System.out.println(userName);
        //json发送到html
        response.setContentType("application/json;charset=utf-8");
        String json = JSONObject.toJSONString(userName);
        response.getWriter().write(json);
    }

    public void getUser(HttpServletRequest request, HttpServletResponse response) throws Exception {
        System.out.println("getUser...");
        //从session获取user
        HttpSession session = request.getSession();
        UserDTO userDTO = (UserDTO) session.getAttribute("userDTO");
        //更新用户信息
        userDTO=userService.getUserById(userDTO.getId());
        //json发送到html
        //System.out.println("g: "+userDTO.getUserType());
        String json = JSONObject.toJSONString(userDTO);
        response.setContentType("application/json;charset=utf-8");
        response.getWriter().write(json);
    //System.out.println("controller:"+userDTO);
    }

    public void addHead(HttpServletRequest request, HttpServletResponse response) throws Exception {
        System.out.println("addHead...");
        response.setContentType("application/json;charset=utf-8");
//            创建DiskFileItemFactory工厂对象
        DiskFileItemFactory factory = new DiskFileItemFactory();
//            设置文件缓存目录，如果该文件夹不存在则创建一个
        File f = new File("D:\\TempFolder");
        if (!f.exists()) {
            f.mkdirs();
        }
        factory.setRepository(f);
//            创建ServletFileUpload对象
        ServletFileUpload fileUpload = new ServletFileUpload(factory);
//            设置字符编码
        fileUpload.setHeaderEncoding("utf-8");
//            解析request，获取FileItem对象
        List<FileItem> fileItems = fileUpload.parseRequest(request);
                String name =new String();
        // 遍历所有字段
        for (FileItem item : fileItems) {
            if (item.isFormField()) { // 普通文本字段
                if ("name".equals(item.getFieldName())) {
                    name = item.getString("UTF-8");
                    //  正确获取文本字段
                }
            }
        }
            System.out.println(name);
        System.out.println(fileItems.size());
        System.out.println(uploadFile(fileItems,0));
    }

    public void composer(HttpServletRequest request, HttpServletResponse response) throws Exception {
        System.out.println("toComposer...");
        //从session获取userId
        HttpSession session = request.getSession();
        UserDTO userDTO = (UserDTO) session.getAttribute("userDTO");
        //json发送到html
        Result result =userService.updateUserToMusicer(userDTO.getId());
        //更新session（userDTO）状态
        userDTO=userService.getUserById(userDTO.getId());
        session.setAttribute("userDTO", userDTO);
        //System.out.println("c: "+userDTO.getUserType());
        response.setContentType("application/json;charset=utf-8");
        response.getWriter().write(JSONObject.toJSONString(result));
    }

    public void managerCode(HttpServletRequest request, HttpServletResponse response) throws Exception {
        System.out.println("managerCode...");
        response.setContentType("application/json;charset=utf-8");
        //从session获取user
        HttpSession session = request.getSession();
        UserDTO userDTO = (UserDTO) session.getAttribute("userDTO");
        //检测是否为管理员
        if(userDTO==null||userDTO.getUserType()!=3){
            response.getWriter().write(JSONObject.toJSONString(Result.fail("不是管理员",null)));
            return;
        }
        //获取管理员验证码
        Result result = verificationCodeService.insertManagerCode(userDTO.getId());
        String managerCode =result.getData().toString();
        System.out.println("managerCode:"+managerCode);
        response.getWriter().write(JSONObject.toJSONString(result));
    }

    public void toBeManager(HttpServletRequest request, HttpServletResponse response) throws Exception {
        System.out.println("toBeManager...");
        response.setContentType("application/json;charset=utf-8");
        //从session获取user
        HttpSession session = request.getSession();
        UserDTO userDTO = (UserDTO) session.getAttribute("userDTO");
        //检测是否为管理员
        if(userDTO.getUserType()==3){
            response.getWriter().write(JSONObject.toJSONString(Result.fail("你已经是管理员了",null)));
            return;
        }
        //获取输入的验证码
        String managerCode = request.getParameter("managerCode");
        //比较 同时service层中‘使用’该验证码
        Result checkAndUse = verificationCodeService.checkAndUseCodeToManager(managerCode);
        if(checkAndUse.getCode()!=200){
            //比较和使用失败
            response.getWriter().write(JSONObject.toJSONString(checkAndUse));
            return;
        }
        //比较和使用成功，变成管理员
        Result manager=userService.updateUserToManager(userDTO.getId());
        //更新session（userDTO）状态
        userDTO=userService.getUserById(userDTO.getId());
        session.setAttribute("userDTO", userDTO);
        //返回结果
        response.setContentType("application/json;charset=utf-8");
        response.getWriter().write(JSONObject.toJSONString(manager));
    }



    public void updateUserWallet(HttpServletRequest request, HttpServletResponse response) throws Exception {
        System.out.println("updateUserWallet...");
        request.setCharacterEncoding("UTF-8");
        String changeValueStr = request.getParameter("changValue");
        //System.out.println("str:"+changeValueStr);

        // 使用 BigDecimal 的构造函数将字符串转换为 BigDecimal
        BigDecimal changeValue = new BigDecimal(changeValueStr);
        //System.out.println("big:"+changeValue);
        //从session获取userId
        HttpSession session = request.getSession();
        UserDTO userDTO = (UserDTO) session.getAttribute("userDTO");
        //调用service
        Result result= userService.updateUserWallet(userDTO.getId(), changeValue);
        //json发送
        response.setContentType("application/json;charset=utf-8");
        response.getWriter().write(JSONObject.toJSONString(result));

    }

    public void updateUserVip(HttpServletRequest request, HttpServletResponse response) throws Exception {
        System.out.println("updateUserVip...");
        request.setCharacterEncoding("UTF-8");
        String daysStr = request.getParameter("days");
        System.out.println(daysStr);
        //字符串转换为 Integer
        Integer days = new Integer(daysStr);
        //从session获取userId
        HttpSession session = request.getSession();
        UserDTO userDTO = (UserDTO) session.getAttribute("userDTO");
        Integer userId = userDTO.getId();
        //调用service
        Result result= userService.updateUserVipEndAt(userId, days);
        //json发送
        response.setContentType("application/json;charset=utf-8");
        response.getWriter().write(JSONObject.toJSONString(result));

    }





}
